package com.amumu.drama.common.modules.invitation.service.impl;

import com.amumu.drama.common.base.api.CommonResult;
import com.amumu.drama.common.modules.invitation.service.InvitationService;
import com.amumu.drama.common.modules.member.service.UmsMemberService;
import com.amumu.drama.mapper.InvitationLogMapper;
import com.amumu.drama.mapper.InvitationMapper;
import com.amumu.drama.model.Invitation;
import com.amumu.drama.model.InvitationLog;
import com.amumu.drama.model.UmsMember;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

@Slf4j
@Service
public class InvitationServiceImpl implements InvitationService {

    @Autowired
    private InvitationMapper invitationMapper;
    @Autowired
    private InvitationLogMapper invitationLogMapper;
    @Autowired
    private UmsMemberService memberService;

    @Override
    public CommonResult<String> validateCode(String invitationCode) {
        if (StringUtils.isBlank(invitationCode)) {
            return CommonResult.failed("validateCode 参数不存在");
        }
        try {
            Invitation invitation = invitationMapper.findByCode(invitationCode);
            if (invitation == null) {
                return CommonResult.failed("邀请码不存在");
            }
            // 检查是否启用
            if (invitation.getStatus() != 1) {
                return CommonResult.failed("邀请码无效");
            }
            // 检查是否有效时间
            LocalDateTime now = LocalDateTime.now();
            if (invitation.getStartTime().isAfter(now)) {
                return CommonResult.failed("邀请码未生效");
            }
            if (invitation.getEndTime().isBefore(now)) {
                return CommonResult.failed("邀请码已过期");
            }
            return CommonResult.success();
        } catch (Exception e) {
            return CommonResult.failed("请稍后重试");
        }
    }

    @Override
    public CommonResult<String> generateInvitationCode(BigDecimal discount, UmsMember member) {
        if (member == null) {
            return CommonResult.failed("会员不存在");
        }
        try {
            Invitation existInvitation = invitationMapper.findByMemberId(member.getId());
            if (existInvitation != null && existInvitation.getStatus() == 1 && existInvitation.getEndTime().isAfter(LocalDateTime.now())) {
                return CommonResult.success(existInvitation.getCode());

            }
            Invitation invitation = new Invitation();
            invitation.setMemberId(member.getId());
            invitation.setStartTime(LocalDateTime.now());
            invitation.setEndTime(LocalDateTime.now().plusYears(1));
            invitation.setStatus(1);
            invitation.setCreator(member.getId().toString());
            invitation.setCode(this.generateInvitationCode(member.getId()));
            invitation.setDiscount(discount);
            invitationMapper.insert(invitation);
            return CommonResult.success(invitation.getCode());
        } catch (Exception e) {
            log.error("创建邀请码失败", e);
            return CommonResult.failed("创建邀请码失败 " + e.getMessage());
        }
    }

    @Override
    public BigDecimal queryInvitationDiscount(String invitationCode) {
        if (StringUtils.isBlank(invitationCode)) {
            return BigDecimal.ONE;
        }

        try {
            // 检查是否存在
            Invitation invitation = invitationMapper.findByCode(invitationCode);
            if (invitation == null) {
                return BigDecimal.ONE;
            }
            // 检查是否启用
            if (invitation.getStatus() != 1) {
                return BigDecimal.ONE;
            }
            // 检查是否有效时间
            LocalDateTime now = LocalDateTime.now();
            if (invitation.getStartTime().isAfter(now) || invitation.getEndTime().isBefore(now)) {
                return BigDecimal.ONE;
            }
            return invitation.getDiscount();
        } catch (Exception e) {
            return BigDecimal.ONE;
        }
    }

    private String generateInvitationCode(long memberId) {
        // 提取成员ID的部分数字
        long memberIdPart = memberId % 1000; // 取最后三位

        // 获取当前时间戳
        LocalDateTime now = LocalDateTime.now();
        String timestampStr = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        long timestampPart = Long.parseLong(timestampStr.substring(timestampStr.length() - 3)); // 取最后三位

        // 合并并截取至指定长度
        long combinedValue = memberIdPart * 1000 + timestampPart;
        String baseCode = String.valueOf(combinedValue);

        // 若不足7位，用随机数补足
        StringBuilder invitationCodeBuilder = new StringBuilder(baseCode);
        while (invitationCodeBuilder.length() < 7) {
            invitationCodeBuilder.append(new Random());
        }

        return invitationCodeBuilder.substring(0, 7);
    }

    /** 查询邀请人数 */
    @Override
    public Long countInvitation(Long memberId) {
        QueryWrapper<InvitationLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(InvitationLog::getInviterMemberId, memberId);
        return invitationLogMapper.selectCount(queryWrapper);
    }
}
